/* eslint-disable react/jsx-no-duplicate-props */
import { doFetch, getFetch } from '@/utils/doFetch';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { useRequest } from 'ahooks';
import { ColorPicker, Input, message, Space, Tag, theme, Tooltip } from 'antd';
import { useEffect, useRef, useState } from 'react';

const defaultColor = [
  '#000000',
  '#000000E0',
  '#000000A6',
  '#00000073',
  '#00000040',
  '#00000026',
  '#0000001A',
  '#00000012',
  '#0000000A',
  '#00000005',
  '#F5222D',
  '#FA8C16',
  '#FADB14',
  '#8BBB11',
  '#52C41A',
  '#13A8A8',
  '#1677FF',
  '#2F54EB',
  '#722ED1',
  '#EB2F96',
  '#F5222D4D',
  '#FA8C164D',
  '#FADB144D',
  '#8BBB114D',
  '#52C41A4D',
  '#13A8A84D',
  '#1677FF4D',
  '#2F54EB4D',
  '#722ED14D',
  '#EB2F964D',
];

const TagElem = ({ tag, handleClose, run, setEditInputValue, setEditInputIndex, isLongTag }) => {

  const [value, setValue] = useState(tag.color ?? '#000000');

  return <Tag
    key={tag.name}
    closable
    style={{
      userSelect: 'none',
      display: 'flex',
      alignItems: 'center',
      paddingLeft: 0,
    }}
    onClose={() => handleClose(tag.id)}
    bordered={false}
  >
    <ColorPicker
      presets={[
        {
          label: '预设颜色',
          colors: defaultColor,
        },
      ]}
      size="small"
      value={value}
      onChange={(val) => {
        setValue(val.toHexString())
      }}
      onOpenChange={(open)=>{
        if(open) return false;
        const params = {
          color: value,
        };
        run({ url: `/projectTag/${tag?.id}`, params: params, method: 'PUT' });
      }}
    ></ColorPicker>
    <span
      style={{ paddingLeft: 4 }}
      onDoubleClick={(e) => {
        setEditInputIndex(index);
        setEditInputValue(tag.name);
        e.preventDefault();
      }}
    >
      {isLongTag ? `${tag.name.slice(0, 20)}...` : tag.name}
    </span>
  </Tag>
};

const Tagedit = ({ max = 20, project, refreshlist }) => {
  const { token } = theme.useToken();
  const [inputVisible, setInputVisible] = useState(false);
  const [inputValue, setInputValue] = useState('');
  const [editInputIndex, setEditInputIndex] = useState(-1);
  const [editInputValue, setEditInputValue] = useState('');
  const inputRef = useRef(null);
  const editInputRef = useRef(null);

  //查询当前项目下的所有标签
  const { data, loading, refresh } = useRequest(
    async () => {
      let res = await getFetch({
        url: '/projectTag',
        params: {
          projectId: project.id,
        },
      });
      return res?.data?.dataList;
    },
    {
      refreshDeps: [project?.id],
    },
  );

  // 更新or 删除项目下的标签
  const { run } = useRequest(
    (params) => {
      return doFetch(params);
    },
    {
      manual: true,
      onSuccess: async () => {
        await refresh();
        await refreshlist();
      },
    },
  );

  useEffect(() => {
    if (inputVisible) {
      inputRef.current?.focus();
    }
  }, [inputVisible]);

  useEffect(() => {
    editInputRef.current?.focus();
  }, [inputValue]);

  const handleClose = (id) => {
    run({ url: `/projectTag/${id}`, params: {}, method: 'DELETE' });
  };

  const showInput = () => {
    setInputVisible(true);
  };

  const handleInputChange = (e) => {
    setInputValue(e.target.value);
  };

  const handleInputConfirm = () => {
    if (!inputValue || inputValue.replace(/\s/g, '') === '') {
      message.destroy();
      setInputVisible(false);
      return;
    }
    if (inputValue && data?.map((it) => it.name).indexOf(inputValue) === -1) {
      const params = {
        projectId: project?.id,
        name: inputValue,
        color: token.colorPrimary,
      };
      run({ url: `/projectTag`, params: params });
    } else {
      if (inputValue) message.warning('已存在的标签名！');
    }
    setInputVisible(false);
    setInputValue('');
  };

  const handleEditInputChange = (e) => {
    setEditInputValue(e.target.value);
  };

  const handleEditInputConfirm = async () => {
    if (!editInputValue || editInputValue.replace(/\s/g, '') === '') {
      message.destroy();
      message.error('标签不可为空字符！');
      return;
    }
    if (
      editInputValue &&
      data
        ?.filter((it, i) => i !== editInputIndex)
        .map((it) => it.name)
        .indexOf(editInputValue) === -1
    ) {
      const newTags = [...data];
      const currentTag = newTags[editInputIndex];

      const params = {
        name: editInputValue,
      };
      run({ url: `/projectTag/${currentTag?.id}`, params: params, method: 'PUT' });
      setEditInputIndex(-1);
      setInputValue('');
    } else {
      message.warning('已存在的标签名！');
    }
  };

  const tagInputStyle = {
    width: 78,
    verticalAlign: 'top',
    height: 26
  };

  const tagPlusStyle = {
    background: token.colorBgContainer,
    borderStyle: 'dashed',
    height: 26,
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    cursor: 'pointer',
    gap: 6
  };

  return (
    loading ?
      <div className="sorts">
        <LoadingOutlined></LoadingOutlined>
      </div>
      :
      <Space wrap style={{ paddingTop: 4, justifyContent: 'flex-start', gap: 8 }}>
        {data?.map?.((tag, index) => {
          if (editInputIndex === index) {
            return (
              <Input
                ref={editInputRef}
                key={tag}
                size="small"
                value={editInputValue}
                onChange={handleEditInputChange}
                onBlur={handleEditInputConfirm}
                onPressEnter={handleEditInputConfirm}
                style={{ ...tagInputStyle }}
              />
            );
          }
          const isLongTag = tag?.name?.length > 20;
          const props = { tag, handleClose, run, setEditInputValue, setEditInputIndex, isLongTag };

          return isLongTag ? (
            <Tooltip title={tag.name} key={tag.name}>
              <TagElem
                {...props}
              ></TagElem>
            </Tooltip>
          ) : (
            <TagElem {...props}></TagElem>
          );
        })}
        {inputVisible ? (
          <Input
            ref={inputRef}
            type="text"
            size="small"
            style={tagInputStyle}
            value={inputValue}
            onChange={handleInputChange}
            onBlur={handleInputConfirm}
            onPressEnter={handleInputConfirm}
          />
        ) : (
          data?.length < max &&
          editInputIndex === -1 && (
            <Tag style={tagPlusStyle} onClick={showInput}>
              <PlusOutlined /> 新建标签
            </Tag>
          )
        )}
      </Space>
  );
};

export default Tagedit;
